import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fluro/fluro.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:math';
import 'package:provider/provider.dart';
import '../../../utils/methods.dart';
import '../../../components/toast.dart';
import '../../../components/circle.dart';
import '../../../routes/routes.dart';
import '../../../provider/model.dart';

class Subject1 extends StatefulWidget {
  @override
  _Subject1State createState() => _Subject1State();
}

class _Subject1State extends State<Subject1> with SingleTickerProviderStateMixin {

  List<Map> leftClassify = [
    {'title': 'VIP课程', 'icon': 'http://www.zhangkang.fun/assets/ljxc/icon1.png'},
    {'title': '专项练习', 'icon': 'http://www.zhangkang.fun/assets/ljxc/icon2.png'},
    {'title': '图标技巧', 'icon': 'http://www.zhangkang.fun/assets/ljxc/icon3.png'},
    {'title': '考前押题', 'icon': 'http://www.zhangkang.fun/assets/ljxc/icon4.png'},
  ];

  List<Map> rightClassify = [
    {'title': '错题·收藏', 'icon': 'http://www.zhangkang.fun/assets/ljxc/icon5.png'},
    {'title': '随机练习', 'icon': 'http://www.zhangkang.fun/assets/ljxc/icon6.png'},
    {'title': '情景练题', 'icon': 'http://www.zhangkang.fun/assets/ljxc/icon7.png'},
    {'title': '天猫特卖', 'icon': 'http://www.zhangkang.fun/assets/ljxc/icon8.png'}
  ];

  AnimationController rotateAc;
  Animation<double> imgRotate;
  double rotateVal = 0.0;
  int sub1ExamsLen = 0;

  @override
  void initState() { 
    super.initState();
    _initController();
    _initAnimation();
    _startAnimation();
    getExamLibs();
  }

  @override
  void dispose() {
    rotateAc?.dispose();
    super.dispose();
  }

  void _initController() {
    rotateAc = AnimationController(
      duration: Duration(seconds: 3),
      vsync: this
    );
  }

  void _initAnimation() {
    imgRotate = Tween<double>(
      begin: 0.0,
      end: pi * 2
    ).animate(
      CurvedAnimation(
        parent: rotateAc,
        curve: Interval(0.0, 1.0, curve: Curves.ease)
      )
    )..addListener(() {
      setState(() {
        rotateVal = imgRotate.value;
      });
    })..addStatusListener((AnimationStatus status) {
      // 监控动画状态
    });
  }

  Future _startAnimation() async {
    try {
      await rotateAc.repeat();
    } on TickerCanceled {
      print('动画失败');
    }
  }

  void getExamLibs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String subject1 = prefs.getString('subject1');
    if(subject1 != null) {
      int len = json.decode(subject1).length;
      Provider.of<SubLenModel>(context, listen: false).setSub1Len(len);
      return;
    }
  }

  // 广告位
  Widget adInfo() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(
        top: fitSize(30),
        bottom: fitSize(20)
      ),
      child: Image.network(
        'http://www.zhangkang.fun/assets/ljxc/guide.png',
        width: fitSize(700),
      ),
    ); 
  }

  // 题目分类
  Widget examClassify() {
    return Container(
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          examClassifyColumn(leftClassify),
          doExercises(),
          examClassifyColumn(rightClassify)
        ],
      ),
    );
  }

  // 题目分类纵列
  Widget examClassifyColumn(List li) {
    List<Widget> cols = [];
    li.forEach((item) {
      Widget classify;
      if(item['title'] == 'VIP课程') {
        classify = Column(
          children: <Widget>[
            GestureDetector(
              onTap: () {
                Toast(
                  context: context,
                  tips: item['title'],
                  icon: Icons.opacity
                ).showToast();
                print(item['title']);
              },
              child: Transform(
                child: Image.network(item['icon'], width: fitSize(80), height: fitSize(80)),
                transform: Matrix4.identity()..rotateY(rotateVal),
                origin: Offset(fitSize(40), fitSize(40)),
              ),
            ),
            SizedBox(height: fitSize(16)),
            Text(item['title'], style: TextStyle(fontSize: fitSize(20))),
            SizedBox(height: fitSize(30))
          ],
        );
      }else{
        classify = Column(
          children: <Widget>[
            GestureDetector(
              onTap: () {
                Toast(
                  context: context,
                  tips: item['title'],
                  icon: Icons.opacity
                ).showToast();
                print(item['title']);
              },
              child: Image.network(item['icon'], width: fitSize(80), height: fitSize(80)),
            ),
            SizedBox(height: fitSize(16)),
            Text(item['title'], style: TextStyle(fontSize: fitSize(20))),
            SizedBox(height: fitSize(30))
          ],
        );
      }
      cols.add(classify);
    });
    return Column(
      children: cols.toList(),
    );
  }

  // 做题按钮
  Widget doExercises1() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        CirclePercent(
          width: fitSize(230),
          percent: 30.0,
          child: GestureDetector(
            onTap: () {
              Routes.router.navigateTo(
                context,
                '/exam/theme',
                transition: TransitionType.inFromRight
              );
            },
            child: Container(
              width: fitSize(188),
              height: fitSize(188),
              decoration: BoxDecoration(
                color: Colors.redAccent,
                shape: BoxShape.circle,
                gradient: const LinearGradient(
                  colors: [Color(0xff48bbfe), Color(0xff1982ff)]
                )
              ),
              
            ),
          ),
        ),
        SizedBox(height: fitSize(140)),
      ],
    );
  }

  Widget doExercises() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Consumer<SubLenModel>(
          builder: (context, sub, child) {
            return CirclePercent(
              width: fitSize(220),
              percent: ((sub.rightNum+sub.errorNum)/sub.sub1Len) * 100,
              lineWidth: fitSize(12),
              foreColor: Color(0xff48bbfe),
              bgColor: Color.fromRGBO(75, 195, 255, 0.3),
              child: GestureDetector(
                onTap: () {
                  Routes.router.navigateTo(
                    context,
                    '/exam/theme',
                    transition: TransitionType.inFromRight
                  );
                },
                child: Container(
                  width: fitSize(188),
                  height: fitSize(188),
                  decoration: BoxDecoration(
                    color: Colors.redAccent,
                    shape: BoxShape.circle,
                    gradient: const LinearGradient(
                      colors: [Color(0xff48bbfe), Color(0xff1982ff)]
                    )
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text('顺序练习', style: TextStyle(color: Colors.white, fontSize: fitSize(30))),
                      SizedBox(height: fitSize(10)),
                      Text('${sub.rightNum+sub.errorNum}' + '/${sub.sub1Len}' , style: TextStyle(color: Colors.white, fontSize: fitSize(24)))
                    ]
                  )
                ),
              ),
            );
          }
        ),
        SizedBox(height: fitSize(80)),
        CirclePercent(
          width: fitSize(220),
          percent: 80.0,
          lineWidth: fitSize(12),
          foreColor: Color(0xff3be2ce),
          bgColor: Color.fromRGBO(59, 226, 206, 0.3),
          child: Container(
            width: fitSize(188),
            height: fitSize(188),
            decoration: BoxDecoration(
              color: Colors.redAccent,
              shape: BoxShape.circle,
              gradient: const LinearGradient(
                colors: [Color(0xff31dac7), Color(0xff11b8c1)]
              )
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('模拟考试', style: TextStyle(color: Colors.white, fontSize: fitSize(30))),
                SizedBox(height: fitSize(10)),
                Text('100%仿真', style: TextStyle(color: Colors.white, fontSize: fitSize(24)))
              ]
            ),
          ), 
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          adInfo(),
          examClassify()
        ],
      )
    );
  }
}